namespace GameNesSL.Cache
{
    using System;
    using nesemu;

    public static class GameCache
    {
        private const string ROMPrefix = "rom";
        private const string StatePrefix = "state";
        private const string ConfigName = "config";


        public static GameFieldConfig GetConfig()
        {
            try
            {
                if (Cache.IsInCache(ConfigName))
                {
                    GameFieldConfig cfg =  GameFieldConfig.LoadState(Cache.GetCache(ConfigName));
                    cfg.Events=new GameFieldEvents();
                    return cfg;
                }
            }
            catch (Exception)
            {
                
            }
            return new GameFieldConfig();
        }

        public static void SetConfig(GameFieldConfig cfg)
        {
            try
            {
                Cache.PutCache(ConfigName, cfg.SaveState());
            }
            catch (Exception)
            {
                
            }
        }

        private static string GetRomCacheName(string id)
        {
            return string.Format("{0}{1}", ROMPrefix, id);
        }

        private static string GetSaveCacheName(string id)
        {
            return string.Format("{0}{1}", StatePrefix, id);
        }

        public static byte[] ReadCacheRom(string id)
        {
            return Cache.GetCache(GetRomCacheName(id));
        }

        public static bool HasRom(string id)
        {
            return Cache.IsInCache(GetRomCacheName(id));
        }

        public static bool HasSave(string id)
        {
            return Cache.IsInCache(GetSaveCacheName(id));
        }

        public static void CacheRom(string id, byte[] romdata)
        {
            Cache.PutCache(GetRomCacheName(id), romdata);

        }

        public static void Save(string id, byte[] savedata)
        {
            Cache.PutCache(GetSaveCacheName(id), savedata);
        }

        public static byte[] Load(string id)
        {
            return Cache.GetCache(GetSaveCacheName(id));
        }

    }
}